package com.bjbn.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bjbn.mapper.*;
import com.bjbn.model.dto.CommonRequest;
import com.bjbn.model.dto.CommonResponse;
import com.bjbn.model.dto.CommonResDataItem;
import com.bjbn.model.entity.*;
import com.bjbn.service.KafkaService;
import com.bjbn.service.ParkingDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * 停车场数据服务实现类
 */
@Slf4j
@Service
public class ParkingDataServiceImpl implements ParkingDataService {

    @Autowired
    private OutdoorParkingSpaceMapper outdoorParkingSpaceMapper;

    @Autowired
    private IndoorParkingSpaceMapper indoorParkingSpaceMapper;

    @Autowired
    private ParkingSpaceStatusMapper parkingSpaceStatusMapper;

    @Autowired
    private EntryInfoMapper entryInfoMapper;

    @Autowired
    private ChargeRecordMapper chargeRecordMapper;

    @Autowired
    private ExitInfoMapper exitInfoMapper;

    @Autowired
    private KafkaService kafkaService;

    @Value("${signature.secret}")
    private String secret;

    @Override
    public CommonResponse saveOutdoorParkingData(CommonRequest request) {
        CommonResponse response = new CommonResponse();
        try {
            // 验证签名
            if (!verifySignature(request)) {
                response.setResult_code(1);
                response.setMessage("参数错误");
                return response;
            }

            // 解析数据
            JSONArray dataArray = JSON.parseArray(request.getData_items());
            List<CommonResDataItem> dataItems = new ArrayList<>();
            boolean allSuccess = true;

            for (int i = 0; i < dataArray.size(); i++) {
                CommonResDataItem item = new CommonResDataItem();
                try {
                    JSONObject dataObj = dataArray.getJSONObject(i);
                    String itemId = dataObj.getString("item_id");
                    item.setItem_id(itemId);

                    // 转换为实体类
                    OutdoorParkingSpace entity = JSON.toJavaObject(dataObj, OutdoorParkingSpace.class);

                    // 保存数据
                    // outdoorParkingSpaceMapper.insert(entity);
                    // 推送到Kafka
                    entity.setId(0L);
                    kafkaService.sendOutdoorParking(entity);
                    item.setCode(0); // 成功
                } catch (Exception e) {
                    log.error("保存室外停车场数据失败: {}", e.getMessage(), e);
                    item.setCode(1); // 失败
                    allSuccess = false;
                }
                dataItems.add(item);
            }

            response.setResult_code(0);
            response.setMessage("成功");
            // 当所有数据项都成功时，data_items设为null
            if (allSuccess) {
                response.setData_items(null);
            } else {
                response.setData_items(dataItems.toArray(new CommonResDataItem[0]));
            }
        } catch (Exception e) {
            log.error("处理室外停车场数据请求失败: {}", e.getMessage(), e);
            response.setResult_code(1);
            response.setMessage("处理请求失败");
        }
        return response;
    }

    @Override
    public CommonResponse saveIndoorParkingData(CommonRequest request) {
        CommonResponse response = new CommonResponse();
        try {
            // 验证签名
            if (!verifySignature(request)) {
                response.setResult_code(1);
                response.setMessage("参数错误");
                return response;
            }

            // 解析数据
            JSONArray dataArray = JSON.parseArray(request.getData_items());
            List<CommonResDataItem> dataItems = new ArrayList<>();
            boolean allSuccess = true;

            for (int i = 0; i < dataArray.size(); i++) {
                CommonResDataItem item = new CommonResDataItem();
                try {
                    JSONObject dataObj = dataArray.getJSONObject(i);
                    String itemId = dataObj.getString("item_id");
                    item.setItem_id(itemId);

                    // 转换为实体类
                    IndoorParkingSpace entity = JSON.toJavaObject(dataObj, IndoorParkingSpace.class);

                    // 保存数据
                    // indoorParkingSpaceMapper.insert(entity);
                    // 推送到Kafka
                    entity.setId(0L);
                    kafkaService.sendIndoorParking(entity);
                    item.setCode(0); // 成功
                } catch (Exception e) {
                    log.error("保存室内停车场数据失败: {}", e.getMessage(), e);
                    item.setCode(1); // 失败
                    allSuccess = false;
                }
                dataItems.add(item);
            }

            response.setResult_code(0);
            response.setMessage("成功");
            // 当所有数据项都成功时，data_items设为null
            if (allSuccess) {
                response.setData_items(null);
            } else {
                response.setData_items(dataItems.toArray(new CommonResDataItem[0]));
            }
        } catch (Exception e) {
            log.error("处理室内停车场数据请求失败: {}", e.getMessage(), e);
            response.setResult_code(1);
            response.setMessage("处理请求失败");
        }
        return response;
    }

    @Override
    public CommonResponse saveParkingSpaceStatusData(CommonRequest request) {
        CommonResponse response = new CommonResponse();
        try {
            // 验证签名
            if (!verifySignature(request)) {
                response.setResult_code(1);
                response.setMessage("参数错误");
                return response;
            }

            // 解析数据
            JSONArray dataArray = JSON.parseArray(request.getData_items());
            List<CommonResDataItem> dataItems = new ArrayList<>();
            boolean allSuccess = true;

            for (int i = 0; i < dataArray.size(); i++) {
                CommonResDataItem item = new CommonResDataItem();
                try {
                    JSONObject dataObj = dataArray.getJSONObject(i);
                    String itemId = dataObj.getString("item_id");
                    item.setItem_id(itemId);

                    // 转换为实体类
                    ParkingSpaceStatus entity = JSON.toJavaObject(dataObj, ParkingSpaceStatus.class);

                    // 保存数据
                    // parkingSpaceStatusMapper.insert(entity);
                    // 推送到Kafka
                    entity.setId(0L);
                    kafkaService.sendParkingSpaceStatus(entity);
                    item.setCode(0); // 成功
                } catch (Exception e) {
                    log.error("保存车位状态数据失败: {}", e.getMessage(), e);
                    item.setCode(1); // 失败
                    allSuccess = false;
                }
                dataItems.add(item);
            }

            response.setResult_code(0);
            response.setMessage("成功");
            // 当所有数据项都成功时，data_items设为null
            if (allSuccess) {
                response.setData_items(null);
            } else {
                response.setData_items(dataItems.toArray(new CommonResDataItem[0]));
            }
        } catch (Exception e) {
            log.error("处理车位状态数据请求失败: {}", e.getMessage(), e);
            response.setResult_code(1);
            response.setMessage("处理请求失败");
        }
        return response;
    }

    @Override
    public CommonResponse saveEntryInfoData(CommonRequest request) {
        CommonResponse response = new CommonResponse();
        try {
            // 验证签名
            if (!verifySignature(request)) {
                response.setResult_code(1);
                response.setMessage("参数错误");
                return response;
            }

            // 解析数据
            JSONArray dataArray = JSON.parseArray(request.getData_items());
            List<CommonResDataItem> dataItems = new ArrayList<>();
            boolean allSuccess = true;

            for (int i = 0; i < dataArray.size(); i++) {
                CommonResDataItem item = new CommonResDataItem();
                try {
                    JSONObject dataObj = dataArray.getJSONObject(i);
                    String itemId = dataObj.getString("item_id");
                    item.setItem_id(itemId);

                    // 转换为实体类
                    EntryInfo entity = JSON.toJavaObject(dataObj, EntryInfo.class);

                    // 保存数据
                    // entryInfoMapper.insert(entity);
                    // 推送到Kafka
                    entity.setId(0L);
                    kafkaService.sendEntryInfo(entity);
                    item.setCode(0); // 成功
                } catch (Exception e) {
                    log.error("保存入场信息数据失败: {}", e.getMessage(), e);
                    item.setCode(1); // 失败
                    allSuccess = false;
                }
                dataItems.add(item);
            }

            response.setResult_code(0);
            response.setMessage("成功");
            // 当所有数据项都成功时，data_items设为null
            if (allSuccess) {
                response.setData_items(null);
            } else {
                response.setData_items(dataItems.toArray(new CommonResDataItem[0]));
            }
        } catch (Exception e) {
            log.error("处理入场信息数据请求失败: {}", e.getMessage(), e);
            response.setResult_code(1);
            response.setMessage("处理请求失败");
        }
        return response;
    }

    @Override
    public CommonResponse saveChargeRecordData(CommonRequest request) {
        CommonResponse response = new CommonResponse();
        try {
            // 验证签名
            if (!verifySignature(request)) {
                response.setResult_code(1);
                response.setMessage("参数错误");
                return response;
            }

            // 解析数据
            JSONArray dataArray = JSON.parseArray(request.getData_items());
            List<CommonResDataItem> dataItems = new ArrayList<>();
            boolean allSuccess = true;

            for (int i = 0; i < dataArray.size(); i++) {
                CommonResDataItem item = new CommonResDataItem();
                try {
                    JSONObject dataObj = dataArray.getJSONObject(i);
                    String itemId = dataObj.getString("item_id");
                    item.setItem_id(itemId);

                    // 转换为实体类
                    ChargeRecord entity = JSON.toJavaObject(dataObj, ChargeRecord.class);

                    // 保存数据
                    // chargeRecordMapper.insert(entity);
                    // 推送到Kafka
                    entity.setId(0L);
                    kafkaService.sendChargeRecord(entity);
                    item.setCode(0); // 成功
                } catch (Exception e) {
                    log.error("保存收费记录数据失败: {}", e.getMessage(), e);
                    item.setCode(1); // 失败
                    allSuccess = false;
                }
                dataItems.add(item);
            }

            response.setResult_code(0);
            response.setMessage("成功");
            // 当所有数据项都成功时，data_items设为null
            if (allSuccess) {
                response.setData_items(null);
            } else {
                response.setData_items(dataItems.toArray(new CommonResDataItem[0]));
            }
        } catch (Exception e) {
            log.error("处理收费记录数据请求失败: {}", e.getMessage(), e);
            response.setResult_code(1);
            response.setMessage("处理请求失败");
        }
        return response;
    }

    @Override
    public CommonResponse saveExitInfoData(CommonRequest request) {
        CommonResponse response = new CommonResponse();
        try {
            // 验证签名
            if (!verifySignature(request)) {
                response.setResult_code(1);
                response.setMessage("参数错误");
                return response;
            }

            // 解析数据
            JSONArray dataArray = JSON.parseArray(request.getData_items());
            List<CommonResDataItem> dataItems = new ArrayList<>();
            boolean allSuccess = true;

            for (int i = 0; i < dataArray.size(); i++) {
                CommonResDataItem item = new CommonResDataItem();
                try {
                    JSONObject dataObj = dataArray.getJSONObject(i);
                    String itemId = dataObj.getString("item_id");
                    item.setItem_id(itemId);

                    // 转换为实体类
                    ExitInfo entity = JSON.toJavaObject(dataObj, ExitInfo.class);

                    // 保存数据
                    // exitInfoMapper.insert(entity);
                    // 推送到Kafka
                    entity.setId(0L);
                    kafkaService.sendExitInfo(entity);
                    item.setCode(0); // 成功
                } catch (Exception e) {
                    log.error("保存出场信息数据失败: {}", e.getMessage(), e);
                    item.setCode(1); // 失败
                    allSuccess = false;
                }
                dataItems.add(item);
            }

            response.setResult_code(0);
            response.setMessage("成功");
            // 当所有数据项都成功时，data_items设为null
            if (allSuccess) {
                response.setData_items(null);
            } else {
                response.setData_items(dataItems.toArray(new CommonResDataItem[0]));
            }
        } catch (Exception e) {
            log.error("处理出场信息数据请求失败: {}", e.getMessage(), e);
            response.setResult_code(1);
            response.setMessage("处理请求失败");
        }
        return response;
    }

    @Override
    public boolean verifySignature(CommonRequest request) {
        // return true;
        try {
            if (request == null || StringUtils.isBlank(request.getTs()) ||
                    StringUtils.isBlank(request.getSn()) || StringUtils.isBlank(request.getData_items())) {
                return false;
            }

            // 构建签名字符串
            String signStr = secret + request.getTs() + request.getData_items();
            // 计算MD5
            String calculatedSn = md5(signStr).toUpperCase();
            log.debug("签名结果：" + calculatedSn);
            // 比较签名
            return calculatedSn.equals(request.getSn());
        } catch (Exception e) {
            log.error("验证签名失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * MD5加密
     */
    private String md5(String str) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytes = md.digest(str.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}